<template>
	<view :data-theme="theme" class="container">
		<!-- 标签补打 -->
		<!-- 头部 -->
		<view class="print_header">
			<!-- 打印时间以及仓库名称 -->
			<view class="header_top">
				<view class="top_left">
					<view class="date">
						{{date}}
					</view>
					<view class="warehouse">
						{{warehouseName}}
					</view>
				</view>
				<view class="top_right">
					<view class="print">
						<!-- @click="show1 = true" -->
						<span v-if="IfLinked == false" @click="toggle('bottom',2)">未连接</span>
						<span v-else-if="IfLinked == true" @click="toggle('bottom',2)">已连接</span>
					</view>
					<view class="help">
						帮助
					</view>
				</view>
			</view>
			<!-- 选择商品 -->
			<view class="header_botton">
				<u--input placeholder="请输入商品名称查询" shape="circle" border="surround" prefixIcon="search"
					prefixIconStyle="font-size: 22px;color: clearable #909399" v-model="serialList.materialName"
					@input="goodsChange"></u--input>
			</view>
		</view>
		<!-- 内容为空 -->
		<view v-if="!serialList.length" class="empty">
			<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png"></u-empty>
		</view>
		<!-- 商品列表信息 -->

		<scroll-view scroll-y="true" class="print_center">
			<!-- 复选框 -->
			<checkbox-group v-model="checked" @change="checkboxGroup">
				<view class="checke_list">
					<!-- 循环下面 -->
					<view class="checke_item" v-for="(item, index) in serialList" :key="index">
						<view class="item_top">
							<checkbox :value="JSON.stringify(item)" :iconColor="bgColor" :checked="item.checked"
								class="round-checkbox" />
							<view class="item_img">
								<u--image :showLoading="true" :src="item.image" width="80px" height="80px"></u--image>
							</view>
							<view class="item_right">
								<span v-if="item.brand">[{{item.brand}}]</span>{{item.productName}} ({{item.skuParam}})
							</view>
						</view>
						<view class="item_bottom" style="font-size: 30rpx;color: #808080;margin: 20rpx 0;">
							<span style="display: inline-block;margin-right: 30rpx;">已打印<span
									style="color: #000;">{{item.hadPrintNumber}}</span></span>
							<span>订购数<span style="color: #000;">{{item.orderNumber}}</span></span>
						</view>
						<view class="item_bottom">
							<view style="color: #808080;margin-right: 10rpx;">打印数</view>
							<!-- <u-number-box :min="0" :max="500" v-model="item.printNumber"></u-number-box> -->
							<uni-number-box :min="0" :max="500" v-model="item.printNumber" />
						</view>
					</view>
				</view>
			</checkbox-group>
		</scroll-view>

		<!-- 弹窗 -->
		<!-- 请选择打印机-提示弹窗 -->
		<popups :bgColor="bgColor" :IfLinked.sync="IfLinked" ref="popupsRefs" :toggleIndex="toggleIndex"
			@goPrintSetting="goPrintSetting" @addCheckboxChange="addCheckboxChange"></popups>

		<!-- 全选框 -->
		<view class="print_footer">
			<view class="checkAll">
				<!-- <u-checkbox-group>
					<u-checkbox :activeColor="bgColor" shape="circle" v-model="isAllChecked" :checked="isAllChecked"
						@change="onCheckAll" label="全选"></u-checkbox>
				</u-checkbox-group> -->
				<checkbox-group  @change="onCheckAll">
					<label class="uni-list-cell uni-list-cell-pd" style="display: flex;line-height: 34rpx;">
						<view>
							<checkbox :checked="isAllChecked"/>
						</view>
						<view>全选</view>
					</label>
				</checkbox-group>
			</view>
			<view>
				商品{{checked.length}}
			</view>
			<view>
				打印{{totalCount}}
			</view>
			<button @click="toPrint('bottom',1)" class="button_footer bg_color">补打</button>
		</view>
	</view>
</template>

<script>
	import popups from '../components/popups/popups.vue'
	import UniSection from '@/components/uni/uni-swipe-action/uni-swipe-action.vue';
	import {
		setThemeColor
	} from '../../../utils/setTheme';
	import {
		getLabelApi,
		serialNumberSupplementApi,
		queryLabelSetUpApi
	} from "@/api/labelPrinting.js"
	import text from '../../../uni_modules/uview-ui/libs/config/props/text';
	let app = getApp();
	export default {
		components: {
			'uni-section': UniSection,
			popups,

		},
		data() {
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,
				// ------------------>
				serialList: [],
				paramsForm: {
					depotId: '',
					isPrint: 1, //0未打印，1已打印
					current: 1,
					size: 10,
				},
				date: '', //日期
				warehouseName: '', //仓库名称
				show: false, //请选择打印机，底部报错弹窗
				IfLinked: false, //打印机是否连接
				toggleIndex: 1, //1未连接，2选择连接打印机
				//------
				isPrintBlankLabel: '', //是否开启打印换品标签，0不打，1打印
				// ------------------>
				isAllChecked: false,
				//	表单收集
				checked: [],
				// serrList: [{
				// 	id: 1,
				// 	image: '',
				// 	brand: '鲱鱼',
				// 	productName: '小黄鱼1袋装',
				// 	skuParam: '罐',
				// 	hadPrintNumber: 12,
				// 	orderNumber: 23,
				// 	printNumber: null,
				// 	checked: false,
				// }]
			};
		},
		onLoad(options) {
			this.bgColor = setThemeColor()
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			let result = JSON.parse(options.item);
			this.paramsForm.depotId = result.warehouseDepotId;
			this.date = result.date;
			this.warehouseName = result.warehouseName;
			this.serialList = result.serialList;
			for (let item of this.serialList) {
				item.checked = false;
			};
			this.getSignUp();
		},
		// 监听选中的数组
		watch: {
			checked(newVal, oldVal) {
				if (this.serialList.length == this.checked.length) {
					this.isAllChecked = true
				} else {
					this.isAllChecked = false
				}
			},
		},
		computed: {
			totalCount() {
				let totalCount = 0;
				let num = 0
				let checked = false
				for (let item of this.serialList) {
					num += item.printNumber;
					checked = this.checked
					if (item.checked) {
						totalCount += item.printNumber;
					}
				}
				return totalCount;
			}
		},
		methods: {
			//获取标签设置状态
			getSignUp() {
				queryLabelSetUpApi().then((res) => {
					this.isPrintBlankLabel = res.data.isPrintBlankLabel;
				})
			},

			//获取列表
			async serialSupplement() {
				let res = await getLabelApi(this.paramsForm);
				this.serialList = res.data.records;
				for (let item of this.serialList) {
					item.checked = false;
				}
			},

			// 搜索框数据改变的事件
			goodsChange(e) {
				// 清除之前的定时器
				clearTimeout(this.timerId)
				// 开启一个新的定时器
				this.timerId = setTimeout(() => {
					this.paramsForm.isPrint = 1;
					this.paramsForm.productName = e;
					this.serialSupplement()
				}, 1500)
			},

			// 全选框
			onCheckAll(val) {
				// console.log(val) //true,false
				// if (val) {
				// 	this.checked = this.serialList.map((item) => JSON.stringify(item));
				// } else {
				// 	this.checked = [];
				// }
				
				let that = this;
				let isAllCheck = val.detail.value.length > 0;
				if (isAllCheck) {
					this.checked = this.serialList.map((item) => JSON.stringify(item));
					for(let item of that.serialList){
						item.checked = true;
					}
				} else {
					this.checked = [];
					for(let item of that.serialList){
						item.checked = false;
					}
				}
			},

			//去设置打印
			goPrintSetting(ele) {
				// console.log(ele)
				this.goPage('/pages/labelPrinting/printSettings/printSettings?item=add')
			},

			goPage(url) {
				uni.navigateTo({
					url
				})
			},

			// 复选框事件
			// checkboxChange(n) {},
			// 单点击复选框事件
			// checkbox1(index, checked, item) {
			// 	this.serialList[index].checked = checked;
			// 	if (checked == true) {
			// 		this.checked.push(this.serialList[index])
			// 	}
			// },

			checkboxGroup(ele) {
				//-----------
				let checkBoxValue = ele.detail.value
				let checkBoxGroup = checkBoxValue.map((item) => JSON.parse(item));
				let items = this.serialList,
					values = checkBoxGroup;
				for (var i = 0, lenI = items.length; i < lenI; ++i) {
					let item = items[i]
					for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
						if (values[j].id === item.id) {
							this.$set(item, 'checked', true)
							break;
						} else {
							this.$set(item, 'checked', false)
						}
					}
				}
				if(values.length == 0){
					for(let item of this.serialList){
						item.checked = false;
					}
				}
				this.checked = checkBoxValue;
			},

			toggle(type, ele) {
				this.toggleIndex = ele;
				this.$refs.popupsRefs.toggle(type, ele);
				this.$refs.popupsRefs.startSearch(); //搜索蓝牙
			},

			// 补打点击事件
			toPrint(type, ele) {
				this.type = type;

				let printCountArray = this.serialList.filter(obj => obj.checked).map(obj => {
					return {
						count: obj.printNumber,
						skuParam: obj.skuParam,
						productName: obj.productName,
						maxData: '保质日期:7天',
						newProductData: '包装日期：2023.12.23',
						priceName: '价格',
						price: '4.9元',
						mustContent: obj.mustContent,
						orderId: obj.orderId,
						codeSearch: '扫码查看更多信息',
						PhoneNumber: '客服400-0616-007',
						printData: `打印日期${this.date}`,
					};
				}); // 提取出所有 checked 属性值为 true 的对象的 count 属性值
				let tables = [];
				for (let item of printCountArray) {
					if (this.isPrintBlankLabel == 0) {
						tables.push({
							templateId: 11,
							values: [`${item.productName}`, `${item.skuParam}`, `${item.count}`]
						})
					}
					for (let i = 0; i < item.count; i++) {
						tables.push({
							templateId: 1,
							values: [`${item.productName}`, `${item.maxData}`, `${item.newProductData}`,
								`${item.priceName}`, `${item.price}`, `${item.mustContent}`, `${item.orderId}`,
								`${item.codeSearch}`, `${item.PhoneNumber}`, `${item.printData}`
							]
						})
					}
				};
				let tablesValue = {
					tables: tables
				}

				if (this.IfLinked == false) {
					//如果未连接打印机，出示弹窗
					this.toggleIndex = ele;
					this.$refs.popupsRefs.toggle(type);
				} else {
					let newObject = this.checked.map((str) => JSON.parse(str)); //字符串转对象
					const ManageData = newObject.map(obj => {
						return {
							id: obj.id,
							printNumber: obj.printNumber,
						}
					}); //保留出的部分属性
					if (ManageData == '') {
						uni.showToast({
							title: '请勾选后打印',
							icon: 'error',
							duration: 2000 // 持续时间为 2 秒
						});
					} else {
						this.$refs.popupsRefs.sendBleLabel(tablesValue); //调用组件打印机事件
						uni.showToast({
							title: '打印成功',
							icon: 'success',
							duration: 2000 // 持续时间为 2 秒
						});
						setTimeout(() => {
							this.serialSupplement()
						}, 1000)
					}
				}
			},
			// 连接打印机事件
			addCheckboxChange(n) {
				this.$refs.popupsRefs.addCheckboxChange(n);
			}
		}
	}
</script>

<style lang="scss">
	// 动态颜色
	.bg_color {
		@include main_bg_color(theme);
	}

	page {
		display: flex;
		height: 100%;
		flex-direction: column;
		overflow: hidden;

		.container {
			display: flex;
			height: 100%;
			flex-direction: column;
			overflow: hidden;
		}

		// 头部内容
		.print_header {
			background-color: white;
			padding: 0px 10px;
			display: flex;
			flex-direction: column;
			justify-content: space-around;
			height: 110px;

			// 打印时间以及仓库名称
			.header_top {
				display: flex;
				justify-content: space-between;

				.top_left {
					display: flex;

					view {
						margin-right: 10px;
						font-weight: bold;
					}

				}

				.top_right {
					display: flex;

					view {
						margin-right: 10px;
						font-weight: bold;
					}
				}
			}

			// 打印相关的数量
			.header_center {
				display: flex;

				view {
					margin-right: 30px;
				}
			}

			// <!-- 选择商品 -->
			.header_botton {
				display: flex;
				justify-content: space-between;
				align-items: center;

				view {
					margin-right: 10px;
					font-weight: bold;
				}
			}
		}

		// 内容为空
		.empty {
			flex: 1;
			height: 100%;
		}

		// 商品列表
		.print_center {
			// margin-top: 10px;
			// background-color: white;
			flex: 1;
			overflow: scroll;

			.checke_list {
				width: 100%;
				margin: 20rpx;

				.checke_item {
					display: flex;
					flex-direction: column;
					// justify-content: space-around;
					// align-items: center;
					background-color: white;
					padding: 20px;
					margin-top: 10px;
					width: 100%;
					border-radius: 20rpx;

					.item_top {
						display: flex;
						// justify-content: space-around;
						align-items: center;

						.item_img {
							margin-right: 10px;

							image {
								width: 50px;
								height: 70px;
							}

						}

						.item_right {
							font-weight: bold;
							line-height: 20px;
						}
					}

					.item_bottom {
						display: flex;
						align-items: center;
						justify-content: flex-end;

						.counter {
							display: flex;
							justify-content: space-between;
							align-items: center;
							width: 100px;
							height: 30px;
							border: 1px solid #ccc;
							border-radius: 5px;
							overflow: hidden;
						}

						// .counter button {
						// 	width: 30px;
						// 	height: 30px;
						// 	background-color: #f2f2f2;
						// 	border: none;
						// 	outline: none;
						// 	font-size: 20px;
						// 	color: #666;
						// }

						.counter text {
							width: 40px;
							height: 30px;
							text-align: center;
							line-height: 30px;
							font-size: 16px;
							color: #333;
						}
					}
				}
			}
		}

		// 弹窗
		.popup-content {
			text-align: center;
			background-color: #fff;
		}

		.popup-content>text {
			font-size: 30rpx;
			font-weight: bold;
			margin: 20rpx 0;
		}

		.popup-height {
			width: 200px;
		}

		.ensure {
			// width: 100%;
			background-color: #fff;
			padding-bottom: 22rpx;
			padding-bottom: calc(22rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
			padding-bottom: calc(22rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/

			// .title {
			// 	font-size: 32rpx;
			// 	color: #282828;
			// 	text-align: center;
			// 	margin: 38rpx 0 36rpx 0;
			// 	position: relative;

			// 	.iconfont {
			// 		color: #808080;
			// 		position: absolute;
			// 		right: 30rpx;
			// 		top: 0;
			// 		font-size: 36rpx;
			// 	}
			// }
			.text.title {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 50rpx;
			}

			.text-left {
				// flex: 1;
				text-align: left;
			}

			.center {
				flex: 1;
				text-align: center;
			}

			.right {
				color: #808080;
				flex: 1;
				text-align: right;
				font-size: 36rpx;
			}
		}

		// 底部内容
		.print_footer {
			display: flex;
			justify-content: space-around;
			align-items: center;
			background-color: white;
			height: 60px;
			// position: fixed;
			// bottom: 0;
			// left: 0;
			// width: 100%;


			view {
				margin-right: 20px;
			}

			.button_footer {
				border-radius: 10rpx;
				// width: 100px;
				padding: 20rpx 40rpx;
				color: #fff;
				@include main_bg_color(theme);
			}
		}
	}
</style>